#!/bin/bash

# 洗护系统数据库备份脚本

set -e

# 配置
DB_CONTAINER="laundry-mysql"
DB_NAME="laundry_care"
DB_USER="laundry_user"
DB_PASSWORD="LaundryPass2024!"
BACKUP_DIR="backups/database"
RETENTION_DAYS=30

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 生成备份文件名
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/laundry_care_$TIMESTAMP.sql"

echo "🗄️ 开始数据库备份..."
echo "数据库: $DB_NAME"
echo "备份文件: $BACKUP_FILE"

# 执行备份
if docker exec "$DB_CONTAINER" mysqldump \
    -u "$DB_USER" \
    -p"$DB_PASSWORD" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --hex-blob \
    --default-character-set=utf8mb4 \
    "$DB_NAME" > "$BACKUP_FILE"; then
    
    echo "✅ 数据库备份成功"
    
    # 压缩备份文件
    gzip "$BACKUP_FILE"
    echo "✅ 备份文件已压缩: ${BACKUP_FILE}.gz"
    
    # 显示备份文件大小
    BACKUP_SIZE=$(du -h "${BACKUP_FILE}.gz" | cut -f1)
    echo "📊 备份文件大小: $BACKUP_SIZE"
    
else
    echo "❌ 数据库备份失败"
    exit 1
fi

# 清理旧备份文件
echo "🧹 清理 $RETENTION_DAYS 天前的备份文件..."
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +$RETENTION_DAYS -delete
echo "✅ 旧备份文件清理完成"

# 显示备份列表
echo "📋 当前备份文件列表:"
ls -lh "$BACKUP_DIR"/*.sql.gz 2>/dev/null || echo "无备份文件"

echo "🎉 数据库备份完成！"
